package com.android.lovely.ui.fragment

import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.android.lovely.R
import com.android.lovely.const.ChatChange
import com.android.lovely.data.HomeTabData
import com.android.lovely.databinding.FragmentChatBinding
import com.android.lovely.framework.BaseFragment
import com.android.lovely.framework.BaseMvvmFragment
import com.android.lovely.ui.viewmodel.ChatViewModel
import com.android.lovely.ui.viewmodel.TransViewModel
import com.google.android.material.tabs.TabLayoutMediator
import com.kotlin.extensions.appContext
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 *
 * @author why
 * @date 2025/3/9 16:54
 */
class ChatMsgFragment : BaseFragment<FragmentChatBinding>() {

    private val mViewModel by activityViewModels<ChatViewModel>()

    val listener = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            if (position == 2) {
                mBinding.tvReadAll.isVisible = false
            } else {
                mBinding.tvReadAll.isVisible = true
            }
        }
    }

    private val adapter by lazy {
        ChatAdapter(childFragmentManager, lifecycle)
    }


    override fun initView() {
        mBinding.rlTop.addStatusBarMarginTop()
        mBinding.viewPager.adapter = adapter
        mBinding.tvReadAll.clickable {
            if (mBinding.tvReadAll.isSelected) {
                mViewModel.readAll()
            }
        }
        mBinding.viewPager.registerOnPageChangeCallback(listener)
        mBinding.viewPager.offscreenPageLimit = adapter.itemCount
        TabLayoutMediator(
            mBinding.llTabLayout,
            mBinding.viewPager,
            getTabConfigurationStrategy()
        ).attach()
        adapter.notifyDataSetChanged()
        mBinding.tvReadAll.isSelected = true
        lifecycleScope.launchSafety {
            mViewModel.unread.collect {
                if (it == 0) {
                    mBinding.tvReadAll.isSelected = false
                } else {
                    mBinding.tvReadAll.isSelected = true
                }
            }
        }
        viewLifecycleOwner.lifecycleScope.launch {
            FlowBus.flowOf<ChatChange>().collectLatest {
                mViewModel.getUnread()
            }
        }
    }

    override suspend fun initData() {

    }

    private fun getTabConfigurationStrategy() =
        TabLayoutMediator.TabConfigurationStrategy { tab, position ->
            tab.text = adapter.getTitle(position)
        }

    override fun onDestroy() {
        super.onDestroy()
        mBinding.viewPager.unregisterOnPageChangeCallback(listener)
    }
}

private class ChatAdapter(fragmentManager: FragmentManager, lifeCircle: Lifecycle) : FragmentStateAdapter(fragmentManager, lifeCircle) {

    private val tabs by lazy {
        mutableListOf(
            HomeTabData(null, appContext.getString(R.string.chat)),
            HomeTabData(null, appContext.getString(R.string.collect)),
            HomeTabData(null, appContext.getString(R.string.heart))
        )
    }

    fun updateTags(tags: List<HomeTabData>) {
        tabs.clear()
        tabs.addAll(tags)
        notifyDataSetChanged()

    }

    override fun getItemCount(): Int {
        return tabs.size
    }

    fun getTitle(position: Int): String {
        return tabs[position].roleName
    }

    fun <T> MutableList<T>.removeRange(fromIndex: Int, toIndex: Int) {
        if (fromIndex >= size) {
            return
        }
        val subList: MutableList<T> = subList(fromIndex, toIndex + 1)
        subList.clear()
    }

    override fun createFragment(position: Int): Fragment {
        return when (position) {
            0 -> {
                ChatHistoryFragment()
            }

            1 -> {
                ChatCollectFragment()
            }

            else -> {
                ChatHeartFragment()
            }
        }
    }


}
